package com.tanhua.backmanage.service;


import cn.hutool.core.convert.Convert;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.backmanage.vo.LoginLogVoQs;
import com.tanhua.backmanage.vo.PageResultQs;
import com.tanhua.dubbo.server.api.LoginLogApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.pojo.LoginLog;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class LoginLogService {

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @Reference(version = "1.0.0")
    private LoginLogApi loginLogApi;

    public void save(LoginLogVoQs loginLogVoQs) {
        LoginLog loginLog = new LoginLog();
        loginLog.setId(ObjectId.get());
        loginLog.setEquipment(loginLogVoQs.getEquipment());

//        //ES获取地址
//        UserLocationVo userLocationVo = userLocationApi.queryByUserId(loginLogVoQs.getUserId());
//        loginLog.setPlace(userLocationVo.getAddress());

        //测试写死
        loginLog.setPlace("中国北京市昌平区建材城西路16号");


        loginLog.setLogTime(Convert.toLong(new Date()));
        loginLog.setUserId(loginLogVoQs.getUserId());

        loginLogApi.save(loginLog);
    }


    /**
     * 查询评论列表
     *
     * @param page
     * @param pageSize
     * @param sortProp  排序字段
     * @param sortOrder ascending 升序 descending 降序
     * @param type
     * @param userId
     * @return
     */
    public PageResultQs queryLoginlog(Integer page, Integer pageSize, String sortProp, String sortOrder, String type, String userId) {

        PageResultQs pageResultQs = new PageResultQs();
        pageResultQs.setPage(page);
        pageResultQs.setPagesize(pageSize);
        PageInfo<LoginLog> pageInfo = loginLogApi.queryLoginlog(page, pageSize, sortProp, sortOrder, userId);
        List<LoginLog> records = pageInfo.getRecords();

        Long pageCount = loginLogApi.queryLoginlogCount(userId);
        Integer ceil = (int) (Math.ceil(pageCount / pageSize)+1);
        pageResultQs.setCounts(Convert.toInt(pageCount));
        pageResultQs.setPages(ceil);

        //填充信息
        List<LoginLogVoQs> loginLogVoQss = new ArrayList<>();

        for (LoginLog record : records) {
            LoginLogVoQs loginLogVoQs = new LoginLogVoQs();
//            loginLogVoQs.setId(Convert.toInt(record.getId()));
//            String = record.getId().toHexString();
            loginLogVoQs.setId(Convert.toInt(record.getId().toHexString()));
            loginLogVoQs.setLogTime(record.getLogTime());
            loginLogVoQs.setPlace(record.getPlace());
            loginLogVoQs.setEquipment(record.getEquipment());
            loginLogVoQss.add(loginLogVoQs);
        }
        pageResultQs.setItems(loginLogVoQss);
        return pageResultQs;
    }
}
